#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace Neatly.Module
{
    public class ModuleManager : Singleton<ModuleManager>
    {
        private readonly List<ModuleBase> m_Modules = new List<ModuleBase>();

        public ModuleBase Get(string name)
        {
            for (int i = 0; i < m_Modules.Count; i++)
            {
                if (m_Modules[i].Name == name)
                {
                    return m_Modules[i];
                }
            }
            return null;
        }

        public T Get<T>() where T : ModuleBase
        {
            return Get(typeof(T).Name) as T;
        }

        public void Add<T>() where T : ModuleBase, new()
        {
            T module = new T();
            Add(module);
        }

        public void Add(ModuleBase module)
        {
            for (int i = 0; i < m_Modules.Count; i++)
            {
                if (m_Modules[i].Name == module.Name)
                {
                    Debug.LogErrorFormat("[Module添加失败] {0}: 已被注册.", module.Name);
                    return;
                }
            }
            m_Modules.Add(module);
        }

        public void Remove<T>() where T : ModuleBase, new()
        {
            Remove(typeof(T).Name);
        }

        public void Remove(string moduleName)
        {
            for (int i = m_Modules.Count - 1; i >= 0; i--)
            {
                if (m_Modules[i].Name == moduleName)
                {
                    m_Modules.RemoveAt(i);
                    return;
                }
            }
            Debug.LogErrorFormat("[Module移除失败] {0}: 未被注册.", moduleName);
        }

        //初始化
        public async UniTask InitModules()
        {
            List<UniTask> taskList = new List<UniTask>();
            foreach (var module in m_Modules)
            {
                taskList.Add(module.Init());
            }
            await UniTask.WhenAll(taskList);
        }

        //登录加载
        public void LoginLoad()
        {
            foreach (var module in m_Modules)
            {
                module.LoginLoad();
            }
        }

        public void Update()
        {
            foreach (var module in m_Modules)
            {
                module.Update(Time.deltaTime);
            }
        }

        public void Dispose()
        {
            for (int i = 0; i < m_Modules.Count; ++i)
            {
                m_Modules[i].Dispose();
            }
            DestroyInstance();
        }
    }
}